package com.xinz.server.socket;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

import com.xinz.srmi.ConfigFactory;
import com.xinz.server.SessionListener;
import com.xinz.server.SpotNettyServer;

public class SpotNettySocketServer extends SpotNettyServer {
	
	SpotNettySocketHandler handler;

	public SpotNettySocketServer(String host, int port, ConfigFactory factory) {
		super(host, port, factory);
		handler = new SpotNettySocketHandler(factory);
	}

	@Override
	protected void startup(int port) {
		ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
		
		// Set up the event pipeline factory.
		bootstrap.setPipelineFactory(new FactorialServerPipelineFactory(handler));
		
		// Bind and start to accept incoming connections.
		bootstrap.bind(new InetSocketAddress(port));
	}
	
	@Override
	public void addSessionListener(SessionListener listener) {
		handler.addSessionListener(listener);
	}

	@Override
	public void removeSessionListener(SessionListener listener) {
		
	}
	
	static public class FactorialServerPipelineFactory implements ChannelPipelineFactory{

		SpotNettySocketHandler handler;
		
		public FactorialServerPipelineFactory(SpotNettySocketHandler handler) {
			this.handler = handler;
		}
		
		@Override
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline pipeline = Channels.pipeline();
			
			// Add the number codec first,
			pipeline.addLast("decoder", new SpotProtocalDecoder());
			pipeline.addLast("encoder", new SpotProtocalEncoder());

			// and then business logic.
			// Please note we create a handler for every new channel
			// because it has stateful properties.
			pipeline.addLast("handler", handler);
						
			return pipeline;
		}
		
	}

}
